package com.zuohuaipan.headine.adapter;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.zuohuaipan.headine.R;
import com.zuohuaipan.headine.bean.NewsSummary;
import com.zuohuaipan.headine.utils.Xutils_image;

import java.util.ArrayList;

/**
 * Created by ASUS on 2017/1/9.
 */

public class XList_adapter extends BaseAdapter {
    Context context;
    ArrayList<NewsSummary> arraylist;
    private final int TYPE1 = 0;
    private final int TYPE2 = 1;
    private final int TYPE3 = 2;
    private LayoutInflater inflater;

    //删除小图标
    ImageView iv_imgx;

    private PopupWindow mCurPopupWindow;

    public XList_adapter(FragmentActivity activity, ArrayList<NewsSummary> arrayList) {
        context = activity;
        this.arraylist = arrayList;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    public int getCount() {
        return arraylist.size();
    }

    @Override
    public Object getItem(int position) {
        return arraylist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder1 vh1 = null;
        ViewHolder2 vh2 = null;
        ViewHolder3 vh3 = null;
        if (convertView == null) {
            int type = getItemViewType(position);
            switch (type) {
                case TYPE1:
                    convertView = inflater.inflate(R.layout.xlv_item1, parent, false);
                    vh1 = new ViewHolder1(convertView);
                    convertView.setTag(vh1);
                    break;
                case TYPE2:
                    convertView = inflater.inflate(R.layout.xlv_item2, parent, false);
                    vh2 = new ViewHolder2(convertView);

                    convertView.setTag(vh2);
                    break;
                case TYPE3:
                    convertView = inflater.inflate(R.layout.xlv_item3, parent, false);
                    vh3 = new ViewHolder3(convertView);

                    convertView.setTag(vh3);
                    break;
            }

        } else {
            switch (getItemViewType(position)) {
                case TYPE1:
                    vh1 = (ViewHolder1) convertView.getTag();
                    break;
                case TYPE2:
                    vh2 = (ViewHolder2) convertView.getTag();
                    break;
                case TYPE3:
                    vh3 = (ViewHolder3) convertView.getTag();
                    break;
            }


        }
        //赋值
        switch (getItemViewType(position)) {
            case TYPE1:
                vh1.tv_title.setText(arraylist.get(position).title);
                vh1.tv_from.setText(arraylist.get(position).source);
                vh1.tv_textnum.setText(arraylist.get(position).replyCount + "评论");
                Xutils_image.display(vh1.iv_img, arraylist.get(position).imgsrc);
                break;
            case TYPE2:
                vh2.tv_title.setText(arraylist.get(position).title);
                vh2.tv_from.setText(arraylist.get(position).source);
                vh2.tv_textnum.setText(arraylist.get(position).replyCount + "评论");
                Xutils_image.display(vh2.iv_img1, arraylist.get(position).imgextra.get(0).imgsrc);
                Xutils_image.display(vh2.iv_img2, arraylist.get(position).imgextra.get(1).imgsrc);
                Xutils_image.display(vh2.iv_img3, arraylist.get(position).imgsrc);
                break;
            case TYPE3:
                vh3.tv_title.setText(arraylist.get(position).title);
                vh3.tv_from.setText(arraylist.get(position).source);
                vh3.tv_textnum.setText(arraylist.get(position).replyCount + "评论");
                break;

        }

        iv_imgx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCurPopupWindow = showTipPopupWindow(v, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(context, position + "", Toast.LENGTH_SHORT).show();
                        arraylist.remove(position);
                        XList_adapter.this.notifyDataSetChanged();
                    }
                });
            }
        });

        return convertView;
    }

    @Override
    public int getViewTypeCount() {
        return 3;


    }

    @Override
    public int getItemViewType(int position) {
        if (arraylist.get(position).imgextra == null) {
            return TYPE1;
        } else if (arraylist.get(position).imgextra.size() == 2) {
            return TYPE2;
        }
        return TYPE3;
    }

    class ViewHolder1 {
        TextView tv_title, tv_from, tv_textnum;
        ImageView iv_img;

        public ViewHolder1(View convertView) {
            tv_title = (TextView) convertView.findViewById(R.id.item1_title);
            tv_from = (TextView) convertView.findViewById(R.id.item1_from);
            tv_textnum = (TextView) convertView.findViewById(R.id.item1_textnum);
            iv_img = (ImageView) convertView.findViewById(R.id.item1_img);
            iv_imgx = (ImageView) convertView.findViewById(R.id.item1_add);
        }
    }

    class ViewHolder2 {
        TextView tv_title, tv_from, tv_textnum;
        ImageView iv_img1, iv_img2, iv_img3;

        public ViewHolder2(View convertView) {
            tv_title = (TextView) convertView.findViewById(R.id.item2_title);
            tv_from = (TextView) convertView.findViewById(R.id.item2_from);
            tv_textnum = (TextView) convertView.findViewById(R.id.item2_textnum);
            iv_img1 = (ImageView) convertView.findViewById(R.id.item2_img1);
            iv_img2 = (ImageView) convertView.findViewById(R.id.item2_img2);
            iv_img3 = (ImageView) convertView.findViewById(R.id.item2_img3);
            iv_imgx = (ImageView) convertView.findViewById(R.id.item2_add);
        }
    }

    class ViewHolder3 {
        TextView tv_title, tv_from, tv_textnum;

        public ViewHolder3(View convertView) {
            tv_title = (TextView) convertView.findViewById(R.id.item3_title);
            tv_from = (TextView) convertView.findViewById(R.id.item3_from);
            tv_textnum = (TextView) convertView.findViewById(R.id.item3_textnum);
            iv_imgx = (ImageView) convertView.findViewById(R.id.item3_add);
        }
    }


    public PopupWindow showTipPopupWindow(final View anchorView, final View.OnClickListener onClickListener) {

        final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.popuw_layout, null);

        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
        // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
        // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小

        final PopupWindow popupWindow = new PopupWindow(contentView,
                contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                onClickListener.onClick(v);
            }
        });

        //调整箭头位置，看的时候注意一下
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                // 自动调整箭头的位置
                autoAdjustArrowPos(popupWindow, contentView, anchorView);
                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
        });

        // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
        popupWindow.setOutsideTouchable(true);

        // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
        popupWindow.setTouchable(true);

        // true时，点击返回键先消失 PopupWindow
        // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
        // false时PopupWindow不处理返回键
        popupWindow.setFocusable(false);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;   // 这里面拦截不到返回键
            }
        });

        // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
        // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
        popupWindow.showAsDropDown(anchorView);

        return popupWindow;
    }

    private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {

        View upArrow = contentView.findViewById(R.id.up_arrow);
        View downArrow = contentView.findViewById(R.id.down_arrow);

        //初始化位置数组
        int pos[] = new int[2];//0：x,1:y
        contentView.getLocationOnScreen(pos);//数组初始化，获得位置信息
        Log.d("contentView", "(" + pos[0] + "," + pos[1] + ")");
        int popLeftPos = pos[0];
        Log.d("popLeftPos", "(" + popLeftPos + ")");

        anchorView.getLocationOnScreen(pos);

        int anchorLeftPos = pos[0];
        Log.d("anchorLeftPos", "(" + anchorLeftPos + ")");
        Log.d("anchorView", "(" + pos[0] + "," + pos[1] + ")");
        Log.d("anchorView", "(" + anchorView.getWidth() + "," + upArrow.getWidth() + ")");

        //箭头的X标
        int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;

        Log.d("arrowLeftMargin", "(" + arrowLeftMargin + ")");

        upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
        downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

        RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
        upArrowParams.leftMargin = arrowLeftMargin;
        RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
        downArrowParams.leftMargin = arrowLeftMargin;
    }

}
